#!/usr/bin/env bash
if [[  -e "./url.txt" ]]; then
	rm -r ./url.txt
fi
if [[  -e "./ftp.html" ]]; then
	rm -r ./ftp.html
fi
wget -q https://www.gnu.org/prep/ftp.html
sed -n '/<a /p' ftp.html | sed 's#<a \([^>]*\)>#--SYN--\1--FIN--#g; s/<//g; s/>//g' | \
sed 's/--SYN--/</g; s/--FIN--[^<]*</></g; s/[^<]*</</; s/--FIN--.*/>/;' | \
sed "s#<[^a>]*href=\([^a-zA-Z>]*\(http\|https\|ftp\)://[^ >]*\)[^>]*># @\1@#g; s/<[^>]*>//g; s/'//g; s/@/ /g" | \
sed 's/[[:space:]]//g' | \
sed '/^$/d' | \
sed 's/\"//g' > url.txt
sed -i '$d' url.txt
sed -i '$d' url.txt
sed -i '1,11d' url.txt
sed -i '1i\https://ftp.gnu.org/gnu/' url.txt
#cat  url.txt |  awk 'NR > 1 {print $3}'| while read x ; do echo `ping -c 3 $x | awk -F '[ /]' 'NR==1 {ip=$2} $1=="round-trip" {print ip,$8}'` & done | sort -n -k2
r=1
a=1
url_index=0
urls=()
urls_ali=()
printf "%-15s %-40s %-10s \n" "row" "网站" "round-trip"
for line in `cat url.txt`
do
  url=$line
  urls[$r]=${url}
  array=(${url//\// })
  urls_ali[$r]=${array[1]}
  #echo "${urls_ali[$r]}"
  #ping -c 3 ${urls_ali[$r]} | awk -F '[ /]' 'NR==1 {ip=$2} $1=="round-trip" {print ip,$8}'
  cur_rtt=`ping -c 3 ${urls_ali[$r]} |awk -F '[ /]' 'NR==1 {ip=$2$3":"} $1=="rtt" {print ip,$7,$8,$9}' | sort -n -k3 | awk '{printf "%-50s %-10s %-10s %-10s\n", $1,$2,$3,$4}' | awk '{printf "%-10s\n", $3}'` >/dev/null 2>&1
  if [[ $r > $a ]]; then
	  if [[ $cur_rtt != "" ]] && [[ $cur_rtt != "connect: 网络不可达" ]] && [[ $cur_rtt != "未知的名称或服务" ]] ;  then
		printf "%-15s %-40s %-10s \n" $r ${urls_ali[$r]} $cur_rtt
		b=$(echo "$cur_rtt" | bc)
		  if [ $(echo "$url_rtt > $b" | bc) -eq 1 ] ; then 
		    url_index=$r
		    url_rtt=$(echo "$cur_rtt" | bc)
		  fi
	  fi
  elif [[ $r == $a ]] ; then
	#echo "$r ${urls_ali[$r]}:$cur_rtt" | awk -F '[ /]' 'NR==1 {print ip,$1,$2,$3}'| awk '{printf "%-15s %-40s %-10s \n",$1 $2 $3}'
	printf "%-15s %-40s %-10s \n" $r ${urls_ali[$r]} $cur_rtt
	url_index=$r
	url_rtt=$(echo "$cur_rtt" | bc)
  fi
  ((r++))
done
#echo "当前最佳为$url_index ${urls_ali[$url_index]} $url_rtt" | awk -F '[ /]' 'NR==1 {print ip,$1,$2,$3}'| awk '{printf "%-15s %-40s %-10s \n",$1 $2 $3}'
printf "当前最佳为%-15s %-40s %-10s \n" $url_index ${urls[$url_index]} $url_rtt
if [[  -e "./url.txt" ]]; then
	rm -r ./url.txt
fi
if [[  -e "./ftp.html" ]]; then
	rm -r ./ftp.html
fi